package com.mytijian.openapi.adapter.alihalt.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mytijian.code.service.MerchantService;
import com.mytijian.openapi.adapter.alihalt.consts.AlihaltConsts;
import com.mytijian.openapi.adapter.alihalt.dao.McodeOrderRelDAO;
import com.mytijian.openapi.adapter.alihalt.exception.AlihaltException;
import com.mytijian.openapi.adapter.alihalt.param.AlihaltPDFReportQueryParam;
import com.mytijian.openapi.adapter.alihalt.result.AlihaltPDFExamReportInfo;
import com.mytijian.openapi.adapter.alihalt.result.AlihaltPDFExamReportResult;
import com.mytijian.openapi.adapter.alihalt.service.AlihaltExamReportService;
import com.mytijian.openapi.core.client.IOpenAPIClient;
import com.mytijian.openapi.core.model.AppConfig;
import com.mytijian.openapi.core.service.OpenApiAppConfigService;

@Service("alihaltExamReportService")
public class AlihaltExamReportServiceImpl implements AlihaltExamReportService {
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	
	@Autowired
	private IOpenAPIClient client;

	@Autowired
	private OpenApiAppConfigService openApiService;
	
	/**
	 * FIXME 电子码和订单关系抽出一个service
	 */
	@Autowired
	private McodeOrderRelDAO mcodeOrderRelDAO;

	
	@Override
	public AlihaltPDFExamReportResult getPDFReport(AlihaltPDFReportQueryParam param) {
		
		String mcode = param.getServiceNumber();
		if (mcode == null) {
			log.warn("[阿里健康] [pdf报告查询] 电子码为空");
			throw new AlihaltException("400", "电子码不能为空");
		}
				
		AppConfig config = openApiService.getConfig(AlihaltConsts.AppName);
		String orderNum = mcodeOrderRelDAO.getOrderNumByMcode(mcode);
		if (orderNum==null) {
			log.warn("[阿里健康] [pdf报告查询] 电子码{} 没有对应的订单",mcode);
			throw new AlihaltException("400", "电子码没有对应的订单");
		}
		
		String encodedBase64 = client.getPDFExamReport(config, orderNum);
		AlihaltPDFExamReportInfo info = new AlihaltPDFExamReportInfo();
		info.setPdfString(encodedBase64);
		
		AlihaltPDFExamReportResult result = new AlihaltPDFExamReportResult();
		result.setResponseCode("200");
		result.setResult(info);
		
		return result;
	}

}
